/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DeviceFirmwareView.java
 *
 * Created on 02.Şub.2010, 11:16:47
 */
package org.testis.gui.mvc.view.testbed;

import org.testis.gui.mvc.controller.TestBedControllerList;
import org.testis.gui.mvc.controller.testbed.DeviceFirmwareController;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.gui.mvc.utilities.ValidationUtils;
import org.testis.gui.mvc.view.AbstractViewPanel;
import org.testis.gui.mvc.view.AtofBaseDialog;
import org.testis.orm.testbed.refined.DeviceDefinitionFactory;
import org.testis.orm.testbed.refined.DeviceDefinitionRefined;
import org.testis.orm.testbed.refined.DeviceFirmwareRefined;
import org.testis.orm.testbed.refined.DynamicMapRefined;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author selcuk
 */
public class DeviceFirmwareView extends AtofBaseDialog implements
        AbstractViewPanel, Validatable {

    private DeviceFirmwareController m_controller;
    private boolean m_editMode;
    private DeviceFirmwareRefined m_firmwareRefined = null;
    private int m_firmwareId;
    private static String NEW_DYNAMIC_MAP_STR = "...New Dynamic Map";

    /** Creates new form DeviceFirmwareView */
    public DeviceFirmwareView(Frame owner, boolean modal, boolean editMode) {
        super(owner, modal);
        m_controller = TestBedControllerList.newInstance().getDeviceFirmwareController();
        m_editMode = editMode;
        initComponents();
        setFrameIcon("images/testbed/" + DeviceFirmwareRefined.TYPE_NAME.toLowerCase(
                Locale.ENGLISH) + ".png");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        descriptionTextArea = new javax.swing.JTextArea();
        nameTextField = new javax.swing.JTextField();
        dynamicMapComboBox = new javax.swing.JComboBox();
        deviceNameComboBox = new javax.swing.JComboBox();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        dynamicMapTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(getWindowTitle());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel1.setText("Name");

        jLabel2.setText("Device Name");

        jLabel3.setText("Dynamic Map");

        jLabel4.setText("Description");

        descriptionTextArea.setColumns(20);
        descriptionTextArea.setRows(5);
        jScrollPane1.setViewportView(descriptionTextArea);

        dynamicMapComboBox.setModel(new DefaultComboBoxModel());
        populateDynamicMapComboBox();
        dynamicMapComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dynamicMapComboBoxActionPerformed(evt);
            }
        });

        deviceNameComboBox.setModel(new DefaultComboBoxModel());
        deviceNameComboBox.setEnabled(false);
        populateDeviceNameComboBox();

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setText("Save");
        setDefaultButton(saveButton);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        jLabel5.setText("New Dynamic Map");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(13, 13, 13)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
                            .addComponent(nameTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
                            .addComponent(deviceNameComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 245, Short.MAX_VALUE)
                            .addComponent(dynamicMapComboBox, 0, 245, Short.MAX_VALUE)
                            .addComponent(dynamicMapTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, saveButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel2)
                    .addComponent(deviceNameComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel3)
                    .addComponent(dynamicMapComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel5)
                    .addComponent(dynamicMapTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cancelButton)
                            .addComponent(saveButton)))
                    .addComponent(jLabel4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        WindowListener[] listeners = getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setVisible(false);
        this.setEnabled(false);
        m_controller.operationCloseWindow();
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (!validateForm()) {
            return;
        }
        saveButton.setEnabled(false);

        String name = nameTextField.getText();
        String desc = descriptionTextArea.getText();
        int deviceId = getSelectedDeviceId();
        int designTreeId = getSelectedDynamicMapDesignTreeId();
        String newDynamicMapName = dynamicMapTextField.getText();
        if (m_editMode) {
            HashMap values = new HashMap();
            values.put("id", m_firmwareId);
            values.put("name", name);
            values.put("deviceId", deviceId);
            values.put("description", desc);
            if (dynamicMapComboBox.getSelectedIndex() != 0) {
                values.put("dmapDesigntreeId", designTreeId);
            } else {
                values.put("newDynamicMapName", newDynamicMapName);
            }
            m_controller.operationSaveFirmware(m_firmwareRefined, values);
        } else {
            if (dynamicMapComboBox.getSelectedIndex() != 0) {
                m_controller.operationAddFirmware(name, deviceId,
                        designTreeId, desc);
            } else {
                m_controller.operationAddFirmware(name, deviceId,
                        newDynamicMapName, desc);
            }
        }
        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void dynamicMapComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dynamicMapComboBoxActionPerformed
        // Get the new item
        Object item = dynamicMapComboBox.getSelectedItem();
        if (item != null && item instanceof String) {
            String itemStr = (String) item;
            dynamicMapTextField.setVisible(itemStr.equals(
                    NEW_DYNAMIC_MAP_STR));
        } else {
            dynamicMapTextField.setVisible(false);
            dynamicMapTextField.setText("");
        }
        jLabel5.setVisible(dynamicMapTextField.isVisible());
    }//GEN-LAST:event_dynamicMapComboBoxActionPerformed

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                DeviceFirmwareController.VISIBLE_PROPERTY)) {
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                DeviceFirmwareController.FIRMWARE_REFINED_PROPERTY)) {
            DeviceFirmwareRefined val = (DeviceFirmwareRefined) evt.getNewValue();
            m_firmwareRefined = val;
        } else if (evt.getPropertyName().equals(
                DeviceFirmwareController.FIRMWARE_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            m_firmwareId = val;
        } else if (evt.getPropertyName().equals(
                DeviceFirmwareController.NAME_PROPERTY)) {
            nameTextField.setText((String) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                DeviceFirmwareController.DEVICE_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectDeviceNameCombobox(val);
        } else if (evt.getPropertyName().equals(
                DeviceFirmwareController.MAP_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectDynamicMapCombobox(val);
        } else if (evt.getPropertyName().equals(
                DeviceFirmwareController.DESCRIPTION_PROPERTY)) {
            descriptionTextArea.setText((String) evt.getNewValue());
        } else if (evt.getPropertyName().equals(
                DeviceFirmwareController.ERROR_PROPERTY)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public boolean validateForm() {
        boolean valid = true;
        StringBuilder builder = new StringBuilder();

        if (dynamicMapComboBox.getSelectedIndex() == 0) {
            if (ValidationUtils.isEmpty(dynamicMapTextField.getText())) {
                builder.append("DynamicMap name must not be empty.\n");
                valid = false;
            }
        }

        if (ValidationUtils.isEmpty(nameTextField.getText())) {
            builder.append("Name must not be empty.\n");
            valid = false;
        }

        if (!valid) {
            JOptionPane.showMessageDialog(null,
                    builder.toString(),
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }

    private void populateDeviceNameComboBox() {
        deviceNameComboBox.removeAllItems();
        List<DeviceDefinitionRefined> list = DeviceDefinitionFactory.newInstance().getDeviceList();
        for (Iterator<DeviceDefinitionRefined> it = list.iterator(); it.hasNext();) {
            DeviceDefinitionRefined obj = it.next();
            deviceNameComboBox.addItem(obj);
        }
    }

    private void populateDynamicMapComboBox() {
        dynamicMapComboBox.removeAllItems();
        dynamicMapComboBox.addItem("...New Dynamic Map");
        DynamicMapRefined[] arr = DynamicMapRefined.getDynamicMapArray();
        if (arr != null) {
            for (int i = 0; i < arr.length; i++) {
                DynamicMapRefined obj = arr[i];
                dynamicMapComboBox.addItem(obj);
            }
        }
    }

    private void selectDeviceNameCombobox(int deviceId) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) deviceNameComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            DeviceDefinitionRefined obj = (DeviceDefinitionRefined) model.getElementAt(
                    i);
            if (obj != null && obj.getId() == deviceId) {
                deviceNameComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private void selectDynamicMapCombobox(int mapId) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) dynamicMapComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            Object obj = model.getElementAt(i);
            if (obj != null && obj instanceof DynamicMapRefined) {
                DynamicMapRefined dynamiMap = (DynamicMapRefined) obj;
                if (dynamiMap.getId() == mapId) {
                    dynamicMapComboBox.setSelectedIndex(i);
                    return;
                }
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextArea descriptionTextArea;
    private javax.swing.JComboBox deviceNameComboBox;
    private javax.swing.JComboBox dynamicMapComboBox;
    private javax.swing.JTextField dynamicMapTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables

    private int getSelectedDeviceId() {
        int result = 0;
        DeviceDefinitionRefined obj = (DeviceDefinitionRefined) deviceNameComboBox.getSelectedItem();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private int getSelectedDynamicMapDesignTreeId() {
        int result = 0;
        Object obj = dynamicMapComboBox.getSelectedItem();
        if (obj != null && obj instanceof DynamicMapRefined) {
            DynamicMapRefined dynamicMapRefined = (DynamicMapRefined) obj;
            if (dynamicMapRefined != null) {
                result = dynamicMapRefined.getDesignTreeId();
            }
        }
        return result;
    }

    private String getWindowTitle() {
        if (m_editMode) {
            return new String("Edit Firmware");
        } else {
            return new String("Add New Firmware");
        }
    }
}
